package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.example.bean.User;
import org.example.config.JwtConfig;
import org.example.exception.UserLoginException;
import org.example.mapper.UserMapper;
import org.example.service.UserService;
import org.example.util.JsonResult;
import org.example.util.ResultTool;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public JsonResult login(User user) {
        //1.连接到数据库 判断账号密码是否正确
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        wrapper.eq("password", user.getPassword());
        wrapper.eq("status", 1);
        User one = getOne(wrapper);
        //1.2错误
        if (one == null) {
            //2.抛异常
            throw new UserLoginException("账号或者密码错误");
        }
        //1.1正确
        //2.生成token
        String token = JwtConfig.getJwtToken(one);
        //3.保存到redis
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        //判断用户是否已经登录
        Boolean hasKey = stringRedisTemplate.hasKey("front_token:" + one.getId());
        if (Boolean.TRUE.equals(hasKey)) {
            throw new UserLoginException("该用户已经登录！");
        }
        ops.set("front_token:"+one.getId(), token,1, TimeUnit.DAYS);
        //返回给前端
        return ResultTool.success(token);

    }
}
